package com.test;

import java.util.Arrays;

public class KthLargest {

    private int k;
    private int[] nums;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.nums = nums;
    }

    public int add(int val) {
        int[] arr;
        if (nums == null || nums.length == 0) {
            arr = new int[1];
            arr[0] = val;
        } else {
            arr = new int[nums.length + 1];
            for (int i = 0; i < nums.length; i++) {
                arr[i] = nums[i];
            }
            arr[nums.length] = val;
        }
        if (k < 1 || k > arr.length) return -1;

        this.nums = arr;
        return partition(arr, 0, arr.length - 1, arr.length - k);
    }

    private int partition(int[] nums, int start, int end, int k) {
        if (start >= end) return nums[k];
        int pivot = nums[(start + end) / 2];
        int left = start;
        int right = end;

        while (left <= right) {
            while (left <= right && nums[left] < pivot) {
                left++;
            }
            while (left <= right && nums[right] > pivot) {
                right--;
            }
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        if (k >= left) {
            return partition(nums, left, end, k);
        }
        if (k <= right) {
            return partition(nums, start, right, k);
        }
        return nums[k];
    }

    public static void main(String[] args) {
        KthLargest est = new KthLargest(1, new int[]{});
        System.out.println(est.add(-3));
        System.out.println(est.add(-2));
        System.out.println(est.add(-4));
        System.out.println(est.add(0));
        System.out.println(est.add(4));
    }
}
